package com.drug.mingkang.controller;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.drug.mingkang.model.*;
import com.drug.mingkang.permission.model.PerUsers;
import com.drug.mingkang.service.*;
import com.drug.mingkang.utils.AuditStatus;
import com.drug.mingkang.utils.ResponseMessage;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * (SellDetail)表控制层
 * 分店销售明细
 *
 * @author wutao
 * @since 2020-08-11 12:00:14
 */
@RestController
@RequestMapping("sellDetail")
public class SellDetailController {
    /**
     * 服务对象
     */
    @Resource
    private SellDetailService sellDetailService; //销售明细

    @Resource
    private ImmSellService immSellService; //销售

    @Resource
    private ImmRepertoryService immRepertoryService; //库存

    @Resource
    private ImmAppearService immAppearService; //出库明细

    @Resource
    private ImmFinanceService immFinanceService; //财务

    @Resource
    private ImmRicherService immRicherService; //财务明细

    @Resource
    private HttpSession session;

    @Resource
    private ResponseMessage responseMessage;


    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("selectOne")
    public SellDetail selectOne(String id) {
        return this.sellDetailService.queryById(id);
    }


    /**
     * 查询全部:零售
     * @param sellDetail
     * @return
     */
    @GetMapping("show")
    public Map<String,Object> show(SellDetail sellDetail){
        List<SellDetail> list = sellDetailService.queryAllByLimit(sellDetail);
        Map<String,Object> map = new HashMap<>();
        map.put("data", list);
        map.put("count", list.size());
        map.put("msg","");
        map.put("code",0);
        return map;
    }

    /**
     * 查询全部:批发
     * @param sellDetail
     * @return
     */
    @GetMapping("shows")
    public Map<String,Object> shows(SellDetail sellDetail){
        List<SellDetail> list = sellDetailService.queryAllByLimits(sellDetail);
        for (SellDetail se : list){
            System.out.println(se.getDrugName()+se.getDrugWho());
        }
        Map<String,Object> map = new HashMap<>();
        map.put("data", list);
        map.put("count", list.size());
        map.put("msg","");
        map.put("code",0);
        return map;
    }

    /**
     * 零售增加
     * @param wl
     * @param memberId
     * @param discount
     * @return
     */
    @PostMapping("insert")
    public ResponseMessage insert(String wl, String memberId, String discount){
        //取Session
        PerUsers perUsers = (PerUsers) session.getAttribute("perUsers");
        String immName = perUsers.getCompanyId();
        ResponseMessage response=new ResponseMessage();
        ImmSell immSell = new ImmSell();
        //总数量
        int num = 0;
        //总价格
        Double sum = 0.00;

        List<SellDetail> list = JSONObject.parseArray(wl, SellDetail.class);
        System.out.println(wl);
        int row=0;
        for(int i = 0; i < list.size(); i++){
            System.out.println("分店id" + immName +"===== 药品id" + list.get(i).getDrugId() );
            ImmRepertory immRepertory=immRepertoryService.selectDrug(immName,list.get(i).getDrugId());

            System.out.println("分店药品总数量" + immRepertory.getCount() +"===== 需要药品数量" + list.get(i).getDetailCount() );
            if(immRepertory.getCount()-list.get(i).getDetailCount()<0){
                row=-1;
                break;
            }
        }
        System.out.println(row);

        List<ImmAppear> immAppearList = new ArrayList<>();
//        List<ImmRicher> immRicherList = new ArrayList<>();
        if (row==0){
            if(StringUtils.isEmpty(discount)){
                discount="1";
                memberId="0";
            }
            for (SellDetail sd : list){
                num += sd.getDetailCount();
                sum += (sd.getDrugRetail()*sd.getDetailCount())*Double.parseDouble(discount);
            }
            //药店
            immSell.setImmId(immName);
            //总数量
            immSell.setSellCount(num);
            //总价格
            immSell.setSellMonty(sum);
            //零售
            immSell.setSellType(0);
            immSell.setDiscount(Double.parseDouble(discount));
            immSell.setOperator(perUsers.getUserName());

            ImmSell imm = immSellService.insert(immSell);

            //加销售ID
            for(int i = 0; i < list.size(); i++){
                Double sums = (list.get(i).getDrugRetail()*list.get(i).getDetailCount())*Double.parseDouble(discount);
                SellDetail sd = list.get(i);
                sd.setSellId(imm.getSellId());
                sd.setMemberId(memberId);
                sd.setOperator(perUsers.getUserName());
                sd.setPrice(sums);
            }
            responseMessage = sellDetailService.insertBatch(list) > 0 ? ResponseMessage.success() : ResponseMessage.error();

            /* 减库存 加明细*/
            for(int i = 0; i < list.size(); i++){
                ImmAppear immApp= new ImmAppear();

                SellDetail sellDetail= list.get(i);
                if(sellDetail.getDetailCount() != null){
                    immApp.setAppearCount(sellDetail.getDetailCount());
                    immApp.setDrugId(sellDetail.getDrugId());
                    //修改库存数量
                    ImmRepertory imma = immRepertoryService.updateOne(immApp,immName);
                    //获取修改库存数量之后的库存ID
                    immApp.setRepertory(imma.getRepertoryId());
                    immApp.setStatus("2");
                    immApp.setOperator(perUsers.getUserName());
                    immAppearList.add(immApp);

                }
            }
            //查询分店ID
            ImmFinance immf = immFinanceService.findByImmName(immName);
            ImmRicher immRicher= new ImmRicher();

            immRicher.setDrugId(imm.getSellId());
            immRicher.setRicherMoney(imm.getSellMonty());
            //修改财务金额
            immFinanceService.updateOne(immRicher,immName);
            //分店ID
            immRicher.setFinanceId(immf.getFinanceId());
            immRicher.setOperator(perUsers.getUserName());
            immRicher.setIsva(1);

            responseMessage = immAppearService.insertBatch(immAppearList) > 0 ? ResponseMessage.success() : ResponseMessage.error();

            responseMessage = immRicherService.insert(immRicher) > 0 ? ResponseMessage.success() : ResponseMessage.error();

        }else{
            response.setStatus(1);
            response.setMessage("分店药品库存不足");
        }

        if(row==0){
            return ResponseMessage.success("保存成功");
        }else{
            return response;
        }

    }

    /**
     * 批发增加
     * @param wl
     * @return
     */
    @PostMapping("inserts")
    public ResponseMessage inserts(String wl){
        //取Session
        PerUsers perUsers = (PerUsers) session.getAttribute("perUsers");
        System.out.println(perUsers.getCompanyId()+"=============================");
        String immName = perUsers.getCompanyId();

        ResponseMessage response=new ResponseMessage();
        //总数量
        int num = 0;
        //总价格
        Double sum = 0.00;
        //明细总价格
        ImmSell immSell = new ImmSell();
        List<SellDetail> list = JSONObject.parseArray(wl, SellDetail.class);
        System.out.println(wl);
        int row=0;
        for(int i = 0; i < list.size(); i++){
            ImmRepertory immRepertory=immRepertoryService.selectDrug(immName,list.get(i).getDrugId());

            if(immRepertory.getCount()-list.get(i).getDetailCount()<0){
                row=-1;
                break;
            }

        }
        System.out.println(row);

        /* 减库存 */
//        List<ImmAppear> immAppearList = new ArrayList<>();
//        List<ImmRicher> immRicherList = new ArrayList<>();
        if (row==0){
            //循环加
            for (SellDetail sd : list){
                num += sd.getDetailCount();
                sum += sd.getDrugWho()*sd.getDetailCount();
            }
            //药店
            immSell.setImmId(immName);
            //总数量
            immSell.setSellCount(num);
            //总价格
            immSell.setSellMonty(sum);
            //批发
            immSell.setSellType(1);
            //设置未审核状态 10
            immSell.setIsva(AuditStatus.NO_SQ.status);
            immSell.setOperator(perUsers.getUserName());
            ImmSell imm = immSellService.insert(immSell);
            //加销售ID
            for(int i = 0; i < list.size(); i++){
                Double sums = list.get(i).getDrugWho()*list.get(i).getDetailCount();
                SellDetail sd = list.get(i);
                sd.setSellId(imm.getSellId());
                sd.setOperator(perUsers.getUserName());
                sd.setPrice(sums);
            }
            //批量增加销售明细
            responseMessage = sellDetailService.insertBatch(list) > 0 ? ResponseMessage.success() : ResponseMessage.error();


        }else{
            response.setStatus(1);
            response.setMessage("分店药品库存不足！");
        }

        //返回
        if(row==0){
            return responseMessage;
        }else{
            return response;
        }
    }

}